package com.googlecode.bpmcenter.util;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class ApplicationContextListener implements ServletContextListener {

	private static final String GROUP_ADMINISTRATORS = "ADMINISTRATOR";
	
	private IdentityService identityService;
	private RepositoryService repositoryService;

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());

		this.identityService = (IdentityService) springContext.getBean("identityService");
		this.repositoryService = (RepositoryService) springContext.getBean("repositoryService");

		setUp();
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
	}

	public void setUp() {
		setUpGroups();
		setUpUsers();
		deployProcess();
	}

	private void setUpGroups() {
    addGroup(GROUP_ADMINISTRATORS, "Administradores");
	}

  public void setUpUsers() {
    addUser("user1", "user1", "User", "01", "steven@foobar.net", GROUP_ADMINISTRATORS);
    addUser("user2", "user2", "User", "02", "patrick@foobar.net", GROUP_ADMINISTRATORS);
}

	private void addGroup(String groupId, String name) {
		if (!groupExists(groupId)) {
			Group group = identityService.newGroup(groupId);
			group.setName(name);
			identityService.saveGroup(group);
		}
	}

	private boolean groupExists(String groupId) {
		return identityService.createGroupQuery().groupId(groupId).singleResult() != null;
	}

	private void addUser(String username, String password, String firstName, String lastName, String email, String group) {
		if (!userExists(username)) {
			User user = identityService.newUser(username);
			user.setFirstName(firstName);
			user.setLastName(lastName);
			user.setEmail(email);
			user.setPassword(password);
			identityService.saveUser(user);
			if (group != null) {
				identityService.createMembership(username, group);
			}
		}
	}

	private boolean userExists(String username) {
		return identityService.createUserQuery().userId(username).singleResult() != null;
	}

	private void deployProcess() {
		if (!isDeployed()) {
			repositoryService.createDeployment().addClasspathResource("ServiceOrder.bpmn").deploy();
		}
	}

	private boolean isDeployed() {
		return repositoryService.createProcessDefinitionQuery().processDefinitionKey("ServiceOrder").singleResult() != null;
	}

}
